/**
 * HQ js
 * v1.0
 */

"use strict";

//定义全局命名空间
var HQ = {};

//版本号
HQ.version = "v1.0";

//配置
HQ.config = {
    msg_push_url_qa: "wss://socket-qa.haoqiao.com", // 消息推送qa地址
    msg_push_url: "wss://socketio.haoqiao.com" // 消息推送正式环境
};

//后台请求地址
HQ.config.ajax_url = "";

//工具集
HQ.util = {};

(function(util){

    /**
     * 遍历
     */
    util.each = function(array, cb){
        for(var key in array){
            cb(key, array[key]);
        }
    };

    var var_type = [];
    //判断数据类型
    util.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(key, name){

        if(typeof(name)=='string'){
            var_type[ "[object " + name + "]" ] = name.toLowerCase();
        }

    });
    util.type = function(obj) {  
        return obj == null ? String(obj) : var_type[ Object.prototype.toString.call(obj) ] || "object";  
    };

    /**
     * 获取元素各种坐标
     */
    var position = {
        getScroll : function(o){
            if(o){
                var scrTop = o.scrollTop();
            }else{
                var scrTop = document.documentElement.scrollTop || document.body.scrollTop;
            }
            return scrTop;
        },
        getObj : function(o){
            if(o){return {width : o.outerWidth(),height : o.outerHeight()};}
            return {width : document.body.clientWidth,height : document.body.clientHeight};
        },
        getMousePosition : function(ev){
            var top = document.documentElement.scrollTop || document.body.scrollTop;
            return { y : ev.clientY + top || ev.pageY,x:ev.clientX + document.documentElement.scrollLeft};
        },
        getView : function(){
            return {width:document.documentElement.clientWidth,height:document.documentElement.clientHeight};
        },
        getBodyElemPosition : function(o){
            return {x : o.offset().left,y : o.offset().top};
        },
        getElemPosition : function(o){
            return {x : o.position().left,y : o.position().top};
        },
        centerPosition : function(o){
            var left = (position.getView().width - position.getObj(o).width)/2,
                top = (position.getView().height - position.getObj(o).height)/3 + position.getScroll();
                if(top < 0 ){ top = 0};
            return {left : left,top : top};
        },
        centerFixPosition : function(o){
            var left = (position.getView().width - position.getObj(o).width)/2,
                top = (position.getView().height - position.getObj(o).height)/2;
            return {left : left,top : top};
        },
        getBg : function(){
            if(document.documentElement.clientHeight > document.body.clientHeight){
                return position.getView();
            }else{
                return position.getObj();
            }
        },
        getPoint : function(o,po){
            var p = position.getBodyElemPosition(o),
                m = position.getObj(o),
                s = position.getScroll(),
                n = position.getObj(po),
                arm_w = 44,
                top = "",
                left = "",
                judge_top = "",
                judge_left = "";
            if(p.y - s < n.height){
                top = p.y + m.height;
                judge_top = 1;
            }else{
                top = p.y - n.height;
                judge_top = 0;
            }
            if(p.x + n.width > position.getView().width){
                left = p.x - n.width + arm_w + m.width/2;
                judge_left = 1;
            }else{
                left = p.x - arm_w + m.width/2;
                judge_left = 0;
            }
            return {left : left,top : top,judge_top : judge_top,judge_left : judge_left};
        }
    };

    util.position = position;

    var show_bg = function(){
        var bg_p = position.getBg(),
            bg_p1 = bg_p.width - 100;
        jQuery("#bg").css({width : $(document).width(), height : $(document).height(), display : "block"});
        if(jQuery.browser.version == 6)
            jQuery("#bg").html("<iframe style='position:absolute;top:0;left:0;z-index:90;width:"+ bg_p1 +"px;height:"+ bg_p.height +"px;filter:alpha(opacity=0)'></iframe>");
    };
	util.show_bg = show_bg;
	
	var show_bg_pm = function(){
        var bg_p = position.getBg(),
            bg_p1 = bg_p.width - 100;
        jQuery("#litter_bg").css({width : "100%", height : "100%", display : "block",filter:"alpha(opacity=0)"});
        if(jQuery.browser.version == 6)
            jQuery("#litter_bg").html("<iframe style='position:absolute;top:0;left:0;z-index:90;width:100%;height:100%;filter:alpha(opacity=0)'></iframe>");
    };
	util.show_bg_pm = show_bg_pm;
	// dialog
    var Dialog = function(){};
    Dialog.prototype = {
        show: function (params) {
            if (!params['title']) { params['title'] = '提示' }
            if (!params['type']) { params['type'] = 'default' }
            if (!params['content']) { console.error('content undefined！--- dialog'); return }
            if (!params['confirmBtnText']) { params['confirmBtnText'] = '确定' }
            // if (params.type === 'textarea' && !params['placeholder']) { params['placeholder'] = '请输入备注信息'; }
            // if (params.type === 'textarea' && !params['length']) { params['length'] = 300; }
            // if (params.type === 'customContent' && !params['customContent']) { console.error('请提供customContent！--- dialog'); return }
            show_bg();
            var _this = this,
                _body = $('body'),
                poi,
                _dialog,
                _dialogHtml = [],
                // textareaHtml = [
                //     '<div class="bg-fff pl30 pr30 pt30 pb20 dif jcc">',
                //         '<div class="dif aic">',
                //             '<div class="hq-dialog-textarea-wrap">',
                //                 '<textarea class="hq-dialog-textarea b-solid b-ddd J_dialog_textarea" placeholder="' + params['placeholder'] + '" maxlength="' + params['length'] + '"></textarea>',
                //                 '<p class="f12 t-999 tar lh1 J_dialog_textarea_length">还能输入' + params['length'] +  '字</p>',
                //             '</div>',
                //         '</div>',
                //     '</div>'
                // ],
                defaultHtml = [],
                bottomHtml = [],
                contHtml = '';
            defaultHtml.push('<div class="bg-fff pl30 pr30 pt30 pb30 dif jcc">');
            defaultHtml.push(  '<div class="dif aic">');
            defaultHtml.push(      '<div class="h100p"><i class="' + (params['icon'] || 'icon_dialog_warn') + '"></i></div>');
            defaultHtml.push(      '<div class="hq-dialog-text f16 J_dialog_text">');
            if(params['main']) {
                defaultHtml.push(      '<p class="f24 t-333 s pb10">' + params['main'] + '</p>');
            }
            if (params.type === 'afterSale') {
                defaultHtml.push(      '<ul class="f16 t-666">' + params['content'] + '</ul>');
            } else {
                defaultHtml.push(      params['content']);
            }
            defaultHtml.push(      '</div>');
            defaultHtml.push(  '</div>');
            defaultHtml.push('</div>');
            // dialog底部按钮
            bottomHtml.push('<a class="radius-4 b-solid b-49f b-5da7ff-hover bg-49f bg-5da7ff-hover t-fff J_dialog_confirm' + (params['confirmCallback'] && typeof params['confirmCallback'] === 'function' ? '' : ' J_dialog_cancel') + '" href="javascript:;">' + params['confirmBtnText'] + '</a>');
            if(params['showCancel'] || params.type === 'default') {
                bottomHtml.push(   '<a class="radius-4 b-solid b-49f bg-49f-hover t-49f t-fff-hover hq-dialog-cancel J_dialog_cancel" href="javascript:;">取消</a>');
            }


            if(!$('.J_dialog_wrap').length) {
                // if(params['maxDialog']) {
                //     _dialogHtml.push('<div class="hq-dialog-wrap max-dialog abs hide J_dialog_wrap">');
                // } else {
                _dialogHtml.push('<div class="hq-dialog-wrap abs hide J_dialog_wrap">');
                // }
                _dialogHtml.push(   '<div class="hq-dialog-title f16 t-fff pl15 pr15 clearfix">');
                _dialogHtml.push(       '<p class="fl J_dialog_title">'+ params['title'] + '</p>');
                // if(params['reload']) {
                //     _dialogHtml.push(       '<i class="iconfont icon-close abs pointer J_dialog_cancel" data-reload="1"></i>');
                // } else {
                    _dialogHtml.push(       '<div class="fr"><i class="iconfont icon-close-s pointer f14 J_dialog_cancel"></i></div>');
                // }
                _dialogHtml.push(   '</div>');
                _dialogHtml.push(   '<div class="J_dialog_cont">');
                // if (params['type'] === 'warn') {
                    _dialogHtml.push(defaultHtml.join(''));
                // } else if (params['type'] === 'textarea') {
                //     // _dialogHtml.push(textareaHtml.join(''));
                // } else if (params.type === 'custom') {
                //     _dialogHtml.push(params['customContent']);
                // }
                _dialogHtml.push(   '</div>');
                _dialogHtml.push(   '<div class="hq-dialog-bottom bg-fff pt10 pb10 b-solid b-top b-e5 dif jcc tac f16 J_dialog_bottom">');
                _dialogHtml.push(   bottomHtml.join(''));
                _dialogHtml.push(   '</div>');
                _dialogHtml.push('</div>');
                _body.append(_dialogHtml.join(''));
            } else {
                // if (params['type'] === 'warn') {
                    contHtml = defaultHtml.join('');
                // } else if (params['type'] === 'textarea') {
                //     // contHtml = textareaHtml.join('');
                // } else if (params.type === 'custom') {
                //     contHtml = params['customContent'];
                // }
                $('.J_dialog_cont').html(contHtml);
                $('.J_dialog_title').text(params['title']);
                // if(params['maxDialog']) {
                //     $('.J_dialog_wrap').addClass('max-dialog');
                // } else {
                //     $('.J_dialog_wrap').removeClass('max-dialog');
                // }
                $('.J_dialog_bottom').html(bottomHtml.join(''));
            }
            _dialog = $('.J_dialog_wrap');
            poi = HQ.util.position.centerPosition(_dialog);
            _dialog.css({top: poi.top}).fadeIn('slow');
            if(params['mounted'] && typeof params['mounted'] === 'function') {
                params.mounted();
            }
            if (params['confirmCallback'] && typeof params['confirmCallback'] === 'function') {
                $('.J_dialog_confirm').unbind().click(function () {
                    params.confirmCallback();
                    return false
                });
            }
        },
        hide: function (reload) {
            $('#bg').fadeOut('slow');
            $('.J_dialog_wrap').fadeOut('slow', function () {
                if(reload) {
                    location.reload();
                }
            });
        },
    };
    util.dialog = new Dialog();
})(HQ.util);


(function(_this, w){

    //判断字符串是否在数组中
    Array.prototype.in_array = function(str){
        for(var i = 0; i < this.length; i++){
            if(this[i] === str){
                return i;
            }
        }
        return false;
    };

    /**
     * 基于jquery Ajax
     * @param  {string}   url     
     * @param  {string}   data    ajax提交参数
     * @param  {Function} cb      成功后回调函数
     * @param  {Function}   errorcb 失败回调函数
     * @param  {string}   method  请求方式
     * @return {[type]}           [description]
     */
    var baseUrl = location.port === '3000'? 'http://api.web.lanccn.com' : 'http://distributor.service.shangtengcar.com';
    var jQ_ajax = function(url, data, cb, fail_cb, method , type){

        if(typeof url !== "string" && url != ""){
            return false;
        }
        var method = method || "post";
        var data = data || "";

        var _toke = localStorage.getItem('_token');
        if (_toke) {
            _toke = JSON.parse(_toke);
        } else {
            _toke = {}
        }
        var ajax = $.ajax({
            url : baseUrl + url,
            type : method,
            data : data,
            timeout: 20000,
            contentType: "application/json;charset=utf-8",
            headers: {
                source: 'web_distribution',
                uid: _toke.user_id,
                cid: _toke.company_id,
                Authorization: _toke.token,
            },
            success : function(data){
                if (data.code === 0) {
                    if(typeof cb === "function"){
                        cb(data);
                    }
                } else {
                    if (fail_cb && typeof fail_cb === 'function') {
                        fail_cb(data);
                    } else if (data.code === 5091 || data.code === 5092 || data.code === 5093 || data.code === 5094 || data.code === 5095 || data.code === 500) {
                        localStorage.removeItem('_token');
                        alert('请登录')
                        location.href = '/'
                    }
                }

            },
            error : function(jqXHR, textStatus, errorThrown){
                if(typeof error_cb === "function"){
                    //error_cb(jqXHR, textStatus, errorThrown);
                }
            }
        });

        return ajax;

    };

    _this.ajax = jQ_ajax;

    _this.getArea = function(cb, id) {
        $.ajax({
            type: 'POST',
            url: 'http://supplier.service.shangtengcar.com/get_area_interface',
            data: JSON.stringify({id: id || 7}),
            contentType: "application/json;charset=utf-8",
            dataType: 'json',
            success: function (data) {
                if (data.code === 0) {
                    !!cb && typeof cb === 'function' && cb(data);
                } else {
                    console.log('获取地址失败！');
                }
            },
            error: function (e) {}
        });
    }

    _this.getArea2 = function(cb) {
        $.ajax({
            type: 'POST',
            url: location.port === '3003'? 'http://api.admin.lanccn.com/get_area_interface' : 'http://supplier.service.shangtengcar.com/area_list',
            data: JSON.stringify({id: 7}),
            contentType: "application/json;charset=utf-8",
            dataType: 'json',
            success: function (res) {
                if (res.code === 0) {
                    var data = res.data[0]._child[45]._child;
                    var list = [];
                    data.forEach(item => {
                        item._child.forEach(l => {
                            delete l._child
                            list.push(l)
                        });
                    });
                    console.log(list)
                    !!cb && typeof cb === 'function' && cb(list);
                } else {
                    console.log('获取地址失败！');
                }
            },
            error: function (e) {}
        });
    }


    /**
     * jsonP
     * @param  {string}   url      url
     * @param  {Function} callback 成功回调函数
     * @return {[type]}            [description]
     */
    var get_json = function(url, callback){
        var _function_rand_name = jsonp_rand();

        var s = document.createElement("script");
        s.src = url + "&cb="+ _function_rand_name +"&t=" + new Date().getTime();
        s.type = "text/javascript";
        s.setAttribute('charset', 'utf-8');
        document.getElementsByTagName("head")[0].appendChild(s);

        window[_function_rand_name] = function(data){
            if(typeof callback === "function"){
                callback(data);
            }
            setTimeout(function(){
                document.getElementsByTagName("head")[0].removeChild(s);
                delete window[_function_rand_name];
            }, 20);
        }

    };
    //生成随机函数，防止多次jsonP加载多个函数覆盖
    function jsonp_rand(){
        return "_Hq"+ Math.floor(Math.random()*10000);
    }

    _this.jsonp = get_json;

    /**
     * 异步加载JS文件
     */
    var get_javascript = function(url, cb){
        var s = document.createElement("script");
        s.src = url;
        s.type = "text/javascript";
        s.setAttribute('charset', 'utf-8');
        document.getElementsByTagName("head")[0].appendChild(s);

        if(s.readyState){
            s.onreadystatechange = function(){
                if (s.readyState == "loaded" || s.readyState == "complete") {
                    s.onreadystatechange = null;
                    cb.call(this);
                }
            };
        }else{
            s.onload = function(){
                cb.call(this);
                s.onload = null;
            };
        }

    };

    _this.get_js = get_javascript;


    /**
     * 设置COOKIE
     * @param {string} name  设置cookie名字
     * @param {string} value cookie设置的值
     * @param {int} times cookie设置时间，单位为天
     */
    _this.set_cookie = function(name, value, times){
        var times = times || 1;
        var ntime  = new Date();
        var domain = location.hostname || '';
        ntime.setTime(ntime.getTime() + times*24*60*60*1000);
        document.cookie = name + "="+ value + ";expires=" + ntime.toGMTString() +";path=/;domain="+ domain;
    };
    /**
     * 获取COOKIE
     * @param  {string} name cookie名字
     * @return {string}      cookie值
     */
    _this.get_cookie = function(name){
        var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
        if(arr != null){
            return arr[2];
        }
        return null;
    };

    /**
     添加事件
     @parameter obj 添加事件对象
     @parameter type 添加事件类型
     @parameter fn 事件函数
    */
    _this.addEven = function(obj, type, fn){
        if(obj.attachEvent){
            obj['e'+type+fn] = fn;
            obj[type+fn] = function(){obj['e'+type+fn](window.event);};
            obj.attachEvent('on'+type, obj[type+fn]);
        }else{
            obj.addEventListener(type, fn, false);
        }
    };

    /*
    多个对象添加事件
    */
    _this.addEvenList = function(obj, type, fn){
        var len = obj.length;
        for( var i=0; i<len; i++ ){
            addEven( obj[i], type, fn );
        }
    };

    /**
     * 鼠标 TIPS
     * @param {object} obj 移动对象
     */
    _this.m_tips = function(obj){
        var is_right = 0;
        var timer = "";

        obj.live("mouseenter", function(ev){
            var cont = $(this).attr("data-tips");
            if(cont == ""){
                return false;
            }
            var cls = $(this).attr("data-cls");
            if(typeof cls == "undefined"){
                cls = "";
            }
            var times = $(this).attr("data-times");
            if(typeof times == "undefined"){
                times = 0;
            }
            timer = setTimeout(function(){
                var html = "<div id='J_m_tips' class='ui-tips "+ cls +"'>"+ cont +"</div>";

                $("body").append(html);

                var m_position = _this.util.position.getMousePosition(ev);

                var width = $("#J_m_tips").outerWidth();
                var win_width = $(window).width();

                if(width + m_position.x > win_width - 40){
                    var left = m_position.x - width - 10;
                    is_right = 1;
                }else{
                    var left = m_position.x + 10;
                    is_right = 0;
                }

                $("#J_m_tips").css({
                    left : left, 
                    top : m_position.y + 10
                });
            }, times);
        });

        obj.live("mousemove", function(ev){
            var m_position = _this.util.position.getMousePosition(ev);

            var width = $("#J_m_tips").outerWidth();

            if(is_right == 1){
                var left = m_position.x - width - 10;
            }else{
                var left = m_position.x + 10;
            }

            $("#J_m_tips").css({
                left : left, 
                top : m_position.y + 10
            });
        });

        obj.live("mouseleave", function(){
            clearTimeout(timer);
            $("#J_m_tips").remove();
        });
    };

    /**
     * 加载图片
     */
    _this.load_img = function(url, cb){
        var img = "";

        delete img.onload;
        delete img.onerror;

        img = new Image();
        
        img.onload = function(){
            (function(img){
                cb && cb(img);
            })(img);
            
            img.onload = null;
        };

        img.onerror = function(){
            (function(img){
                cb && cb(img);
            })(img);

            tj && tj.img_load_error(url);

            img.onerror = null;
        };

        img.src = url;

    };

    /**
     * 延迟加载
     */
    _this.lazy_load = function(){
        var laze_load_timer = "";
        $(window).scroll(function(){
            //clearTimeout(laze_load_timer);

            //laze_load_timer = setTimeout(function(){
                _this.list_img_load();
            //}, 200);
        });
    };

    /**
     * 列表图片加载
     */
    _this.list_img_load = function(){
        var scroll_top = $(window).scrollTop();

        $(".J_lazy_img").each(function(){
            var img_offset_top = $(this).offset().top;
            var window_height = $(window).height();
            var that = $(this);

            if(scroll_top + 500 + window_height >= img_offset_top && scroll_top < img_offset_top){
                var img_src = $(this).attr("data-src");

                _this.load_img(img_src, function(img){

                    var style = that.attr("data-style");

                    that.attr("src", img_src).attr("class", "").attr("style", style).hide().fadeIn(300);

                });
            }
            if(scroll_top + 500 + window_height < img_offset_top){
                return false;
            }
        });
    };

    /**
     * 客服功能
     * @return {[type]} [description]
     */
    _this.customer_service = function(){

        if(typeof config != "undefined"){
            var html = '<div class="popup" style="border:solid 3px #000;" id="J_popup_feadback"><a class="close" id="J_close_feadback" href="javascript:;" title="'+HQ.config.language.common[language][5]+'">'+HQ.config.language.common[language][5]+'</a><div style="position:relative;line-height:34px;padding:0 0 0 300px;"><div style="position:absolute;top:18px;left:60px;text-align:center;"><img src="https://img.haoqiao.com/website/images/kf_dr_icon.jpg" /></div><div class="feadback-cont" style="position:relative;width:auto;height:auto;padding:20px 50px 20px 40px;font-weight:500"><div style="font-size:40px;margin:20px 0 30px 0">'+HQ.config.language.main[language][0]+'</div><div>'+HQ.config.language.main[language][1]+'</div><div>'+HQ.config.language.main[language][2]+'</div><div>'+HQ.config.language.main[language][3]+'</div><div>'+HQ.config.language.main[language][4]+'<span style="color:#d75;font-size:16px;">'+HQ.config.language.main[language][5]+'</span></div><p style="margin:25px 0 0 0"></p></div></div></div>';

            var is_show_feadback = _this.get_cookie("hq_show_feadback");
            if(config.pv != 0 && is_show_feadback != 1){
                var pv_num = _this.get_cookie("hq_pv_num");
                if(pv_num == null){
                    _this.set_cookie("hq_pv_num", 1, 1);
                }else{
                    if(pv_num >= config.pv){
                        _this.set_cookie("hq_pv_num", 0, 0);
                        _this.set_cookie("hq_show_feadback", 1, 10);

                        $("body").append(html);
                        var feadback_obj = $("#J_popup_feadback");
                        var poition = HQ.util.position.centerPosition(feadback_obj);
                        feadback_obj.css({left : poition.left, top : poition.top, display : "block"});
                        HQ.util.show_bg();

                        $("#J_close_feadback").click(function(){
                            $("#J_popup_feadback").hide();
                            $("#bg").hide();
                            return false;
                        });
                    }else if(is_show_feadback != 1){
                        var num = parseInt(pv_num) + 1;
                        _this.set_cookie("hq_pv_num", num, 1);
                    }
                }
            }
        }

    };

})(HQ, window);

$(function(){
    //面包屑
    $(".J_breadcrumb_arrow").click(function(){
        var is_show = $(this).attr("data-show");
        if(is_show == 0){
            $(this).attr("data-show", 1).parent().addClass("breadcrumb-trail-nav-cur");
        }else{
            $(this).attr("data-show", 0).parent().removeClass("breadcrumb-trail-nav-cur");
        }
    });
    //用户签到处理
    var J_signin_button_click = true;
    $('#J_signin_button').unbind(); // 移除重复监听
    $("#J_signin_button").on('click',function (event) {
        if (!J_signin_button_click) return false;
        J_signin_button_click = true;
        $("#sign-button button").addClass('sign-active');
        event.stopPropagation();
        if($(this).attr("data-id") > 0) {
            return false;
        }
        HQ.ajax("/points/user_signin/", {}, function(res){
            if(res.status == 200){
                
                //签到成功将签到按钮设置为不可点击
                $("#J_signin_button").text(HQ.config.language.main[language][6]);
                $("#J_signin_button").addClass("has-sign-btn");
                $("#J_signin_button").attr('data-id', "1");
                $("#sign-menu").children("p").remove();
                
                //$("#sign-menu").append('<p class="point-popup-text"><em class="alpha1">已连续签到</em><em class="times"><i class="color-orange margin-right-5">'+res.data.days+'</i>天</em></p>');
                
                var points_show = 6;
                
                //连续签到超过6天，获得积分恒等于10
                if(res.data.days >= 6) {
                    points_show = 10;
                }else{
                    points_show = res.data.days + 5;
                }
                
                $("#sign-menu").append('<p class="sign-in-left">'+HQ.config.language.main[language][7]+'&nbsp;<span>+'+points_show+'</span>&nbsp;'+HQ.config.language.attr_map_ch[language][4]+'</p>');
            }
            J_signin_button_click = true;
        }, function(){}, "POST");

    });
});    

HQ.tj = function(){

    /* 后台提交地址 */
    var tj_url = "/ajax/tj";
    /* 获取用户屏幕分辨率 */
    var resolution = window.screen;
    /* user agent */
    if(navigator.appName == 'Microsoft Internet Explorer'){
        var agent = navigator.userAgent;
    }else if(window.navigator != ""){
        var agent = window.navigator.userAgent;
    }else{
        var agent = "-";
    }
    if(resolution.width == ""){
        var width = "-";
        var height = "-";
    }else{
        var width = resolution.width;
        var height = resolution.height;
    }
    var url = encodeURIComponent(window.location.href);
    if(url == ""){
        url = "-";
    }
        

    /* 需要记录的用户信息，屏幕分辨率，浏览器信息 */
    var user_msg = width +"\t"+ height +"\t"+ agent;

    /* 页面加载时间统计 */
    var page_load_time = function(){
        if(typeof start_time == "undefined"){
            return false;
        }
        var end_time = new Date().getTime();//加载结束时间
        //统计文档加载完成时间统计
        HQ.ajax(tj_url, {type : 4, loading_time : (end_time-start_time)/1000, url : url, info : user_msg});
        /* 绑定window onload 事件，页面加载完成时间统计 */
        HQ.addEven(window, "load", function(){
            var end_time = new Date().getTime();//加载结束时间

            HQ.ajax(tj_url, {type : 0, loading_time : (end_time-start_time)/1000, url : url, info : user_msg});
        });
    };

    /**
     * 谷歌地图加载时间统计
     */
    var google_map_time = function(){
        if(typeof start_time == "undefined"){
            return false;
        }
        var end_time = new Date().getTime();//加载结束时间

        HQ.ajax(tj_url, {type : 1, loading_time : (end_time-start_time)/1000, url : url, info : user_msg});
    }

    /* 按钮埋点统计 */
    /*var btn_click = function(action){
        HQ.ajax(tj_url +"_btnclick", {type : 3, action : action, url : url, info : user_msg});
    }*/
	/*订单填写页临时统计*/
	var sbtn_click = function(action){
		HQ.ajax(tj_url +"_sbtnclick", {type : 3, action : action, url : encodeURIComponent(window.location.href), info : user_msg});
	}


    /* 满房统计 */
    var full_room = function(action){
        HQ.ajax(tj_url +"_btnclick", {type : 5, action : action, url : url, info : user_msg});
    }

    /* 搜索点击统计 */
    var sea_click = function(action){
        HQ.ajax(tj_url +"_seaclick", {action : action +"\thomepage", info : agent});
    }
	/* 首页广告统计 */
    var ad_click = function(action){
        HQ.ajax(tj_url +"_adclick", {action : action +"\thomepage", info : agent,path : "/mnt/data/logs/logs_index_ad/"});
    }
	/* 房型筛选统计 */
    var price_filter_click = function(action){
        HQ.ajax(tj_url +"_adclick", {action : action +"\thomepage", info : agent,path : "/mnt/data/logs/logs_price_filter/"});
    }

    /* 统计房型价格 */
    var room_price = function(msg){
        HQ.ajax(tj_url +"_room_price", {msg : msg});
    }
    /* 弹窗选项统计 */
    var pop_click = function(action){
        HQ.ajax(tj_url +"_adclick", {action : action, info : agent,path : "/mnt/data/logs_2b/logs_pop_choice/"});
    }
    /* 新手引导统计 */
    var walkthrough_click = function(action){
        HQ.ajax(tj_url +"_adclick", {action : action, info : agent,path : "/mnt/data/logs_2b/logs_walkthrough/"});
    }
    /* 登录位置统计 */
    var login_position = function(action){
        HQ.ajax(tj_url +"_adclick", {action : action, info : agent,path : "/mnt/data/logs_2b/logs_login_position/"});
    }
    /* 价格位置登录弹窗统计 */
    var hotelprice_login_pop_click = function(action){
        HQ.ajax(tj_url +"_adclick", {action : action, info : agent,path : "/mnt/data/logs_2b/logs_hotelprice_login_pop/"});
    }
	/* 供应商响应统计 */
    var hotel_detail_sp = function(action){
        HQ.ajax(tj_url +"_adclick", {action : action, info : agent,path : "/mnt/data/logs_2b/logs_hoteldetail_sp/"});
    }
	/* 供应商召回监控 */
    var hotel_detail_recall = function(action){
        HQ.ajax(tj_url +"_adclick", {action : action, info : agent,path : "/mnt/data/logs/logs_hotelprice/"});
    }
    /* 收银台按钮、弹窗统计 */
    var tj_cashier = function(action){
        HQ.ajax(tj_url +"_adclick", {action : action, info : agent,path : "/mnt/data/logs_2b/logs_cashier_check/"});
    }

    /* 图片加载错误 */
    var img_load_error = function(src, map){
        if(map == "map"){
            var info = encodeURIComponent("GOOGLEMAP\t");
        }else{
            var info = encodeURIComponent("IMAGE|"+ src +"\t");
        }
        var img_date = new Date().getTime();
        HQ.ajax(tj_url +"_error", {action : "E", info : info + encodeURIComponent(window.location.href) +"|"+ (img_date - start_time)});
    };
    
    return {
        page : page_load_time,
        google_map : google_map_time,
        btn_click : function () {

        },
        sbtn_click : sbtn_click,
        full_room : full_room,
        sea_click : sea_click,
        img_load_error : img_load_error,
        room_price : room_price,
        ad_click : ad_click,
        price_filter_click : price_filter_click,
        pop_click : pop_click,
        walkthrough_click : walkthrough_click,
        login_position:login_position,
        hotelprice_login_pop_click:hotelprice_login_pop_click,
        hotel_detail_sp:hotel_detail_sp,
        hotel_detail_recall:hotel_detail_recall,
        tj_cashier:tj_cashier
    };
};

/* 初始化 */
var tj = HQ.tj();

/* fix google maps ie bug */
(function() {
    var head = document.getElementsByTagName("head")[0];
    var head_insert_before = head.insertBefore;
    head.insertBefore = function(elm, doc) {
        if (elm.href && elm.href.indexOf("http://fonts.googleapis.com/css?family=Roboto") === 0) {
            return;
        }
        head_insert_before.call(head, elm, doc);

        return this;
    };

    // var heads = document.getElementsByTagName("head");
    // if(heads){
    //     var head = heads[0];
    //     if(head.appendChild && head._original_appendChild_ === undefined){
    //         head._original_appendChild_ = head.appendChild;
    //         head.appendChild = function(node){
    //             if(node.nodeName == "SCRIPT" && node.src && node.src.indexOf("https://maps.googleapis.com/maps/api/js")==0){
    //                 node.src = node.src.replace(/^https:\/\/maps.googleapis.com/, "https:\/\/maps.googleapis.cn");
    //             }
    //             return head._original_appendChild_(node);
    //         }
    //     }
    // }


})();

//时间格式化函数
function format_date_en(date) {
    var date_temp = {};
    var data_month_en = {"Jan":"01","Feb":"02","Mar":"03","Apr":"04","May":"05","Jun":"06","Jul":"07","Aug":"08","Sept":"09","Oct":"10","Nov":"11","Dec":"12"};
    date_temp= date.split("-");
    if (data_month_en[date_temp[0]] != undefined){
        date =date_temp[2]+'-'+data_month_en[date_temp[0]]+'-'+date_temp[1]
    }
    return date;
}



//浏览器类型及版本
function getBrowserInfo() {
    var agent = navigator.userAgent.toLowerCase();
    var regStr_ie = /msie [\d.]+;/gi;
    var regStr_ff = /firefox\/[\d.]+/gi
    var regStr_chrome = /chrome\/[\d.]+/gi;
    var regStr_saf = /safari\/[\d.]+/gi;
    var isIE = agent.indexOf("compatible") > -1 && agent.indexOf("msie" > -1); //判断是否IE<11浏览器
    var isEdge = agent.indexOf("edge") > -1 && !isIE; //判断是否IE的Edge浏览器
    var isIE11 = agent.indexOf('trident') > -1 && agent.indexOf("rv:11.0") > -1;
    if (isIE) {
        var reIE = new RegExp("msie (\\d+\\.\\d+);");
        reIE.test(agent);
        var fIEVersion = parseFloat(RegExp["$1"]);
        if (fIEVersion == 7) {
            return "IE/7";
        } else if (fIEVersion == 8) {
            return "IE/8";
        } else if (fIEVersion == 9) {
            return "IE/9";
        } else if (fIEVersion == 10) {
            return "IE/10";
        }
    } //isIE end
    if (isIE11) {
        return "IE/11";
    }
    //firefox
    if (agent.indexOf("firefox") > 0) {
        return agent.match(regStr_ff);
    }
    //Safari
    if (agent.indexOf("safari") > 0 && agent.indexOf("chrome") < 0) {
        return agent.match(regStr_saf);
    }
    //Chrome
    if (agent.indexOf("chrome") > 0) {
        return agent.match(regStr_chrome);
    }
}

